/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * InvulgoTracker
 * Copyright (C) Thomas Andersen 2011 <thomas.1.andersen@gmail.com>
 * 
 * InvulgoTracker is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * InvulgoTracker is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include "util.h"

#include "day.h"
#include "config.h"



#define MY_ENCODING "ISO-8859-1"


Day::Day(gint year, gint month, gint day)
{
    this->year = year;
    this->month = month;
    this->day = day;
    dir = NULL;
}

Day::~Day()
{
    if (dir)
        closedir(dir);
}


void Day::FindFiles()
{
    char *filename = new char[PATH_MAX+1];

    sprintf(filename, "%s%s",g_get_home_dir(),"/.InvulgoTracker/");

    if (dir)
        closedir(dir);

    dir = opendir(filename);

    delete[] filename;
}

bool Day::FindNext(int &y, int &m, int &d)
{
    bool found = FALSE;

    if (dir) {
        while(!found && !readdir_r(dir, &entry, &result) && result) {
            if (strlen(result->d_name)>3 && !memcmp(result->d_name, "day", 3)) {
                sscanf(result->d_name,"day%4d%2d%2d", &y, &m, &d);
                if (year == -1 || year == y)
                    if (month == -1 || month == m)
                        if (day == -1 || day == d)
                            found = TRUE;
            }
        } 
    }

    return found;
}

void Day::Load(IDayLoad *rec)
{
    xmlDocPtr doc;
    char *filename = new char[PATH_MAX+1];

    sprintf(filename, "%s%sday%.4d%.2d%.2d.xml",g_get_home_dir(),"/.InvulgoTracker/", this->year, this->month, this->day);

    if (!access(filename, F_OK)) {
        doc = xmlParseFile(filename);

        if (doc) {
            xmlNodePtr cur;
            cur = xmlDocGetRootElement(doc);
            if (!xmlStrcmp(cur->name, (const xmlChar *) "TimeList")) {
                cur = cur->xmlChildrenNode;
                while (cur != NULL) {
                    if ((!xmlStrcmp(cur->name, (const xmlChar *)"TaskTime"))){
                        ParseTime(rec, doc, cur);
                    }
                     
                cur = cur->next;
                }
            }
            xmlFreeDoc(doc);
        }
    }
    delete[] filename;
}


void Day::ParseTime(IDayLoad *rec, xmlDocPtr doc, xmlNodePtr cur)
{
    xmlChar *name = NULL;
    xmlChar *timeStr = NULL;
    xmlChar *key;
    TaskId id;

    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Description"))) {
            name = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
            gchar *tmp = ConvertOutput (name, MY_ENCODING);
            if (tmp)
            {
                xmlFree(name);
                name = (xmlChar*)tmp;
            }
         }
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"Time"))) {
            timeStr = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
            gchar *tmp = ConvertOutput (timeStr, MY_ENCODING);
            if (tmp)
            {
                xmlFree(timeStr);
                timeStr = (xmlChar*)tmp;
            }
         }
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"TaskId"))) {
            key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
            id = TaskId((gchar *)key);
            xmlFree(key);
         }
    cur = cur->next;
    }
    if (name)
        rec->Data((gchar*)name, (gchar*)timeStr, id);
}


void Day::SaveInit()
{
    int rc;
    xmlChar *tmp;

    /* Create a new XmlWriter for DOM, with no compression. */
    this->writer = xmlNewTextWriterDoc(&this->doc, 0);
    if (this->writer == NULL) return;


    /* Start the document with the xml default for the version,
     * encoding ISO 8859-1 and the default for the standalone
     * declaration. */
    rc = xmlTextWriterStartDocument(this->writer, NULL, MY_ENCODING, NULL);
    if (rc < 0) return;

    /* Start an element named "EXAMPLE". Since thist is the first
     * element, this will be the root element of the document. */
    rc = xmlTextWriterStartElement(this->writer, BAD_CAST "TimeList");
    if (rc < 0) return;

    tmp = ConvertInput("List of task-times for InvulgoTracker. See www.invulgo.dk for details.", MY_ENCODING);
    rc = xmlTextWriterWriteComment(this->writer, tmp);
    if (tmp != NULL) xmlFree(tmp);
    if (rc < 0) return;
}

void Day::SaveData(gchar *name, gchar *timeStr, TaskId value)
{
    xmlChar *tmp;

    xmlTextWriterStartElement(this->writer, BAD_CAST "TaskTime");
    tmp = ConvertInput(name, MY_ENCODING);
    xmlTextWriterWriteFormatElement(this->writer, BAD_CAST "Description","%s", tmp);
    if (tmp != NULL) xmlFree(tmp);
    tmp = ConvertInput(timeStr, MY_ENCODING);
    xmlTextWriterWriteFormatElement(this->writer, BAD_CAST "Time","%s", tmp);
    if (tmp != NULL) xmlFree(tmp);
    xmlTextWriterWriteFormatElement(this->writer, BAD_CAST "TaskId","%s", (const gchar *)value);
    xmlTextWriterEndElement(this->writer);
}


void Day::SaveFinal()
{
    int rc = xmlTextWriterEndElement(this->writer);
    if (rc < 0) return;

    rc = xmlTextWriterEndDocument(this->writer);
    if (rc < 0) return;

    xmlFreeTextWriter(this->writer);

    char *filename = new char[PATH_MAX+1];
    
    sprintf(filename, "%s%sday%.4d%.2d%.2d.xml",g_get_home_dir(),"/.InvulgoTracker/", this->year, this->month, this->day);
    
    xmlSaveFormatFile(filename, this->doc, 1);

    delete[] filename;

    xmlFreeDoc(doc);
}
